import { ITodo, TODO_STATUS } from "@/typing"
import { watch } from "vue";
import { Store, useStore } from "vuex"

export interface IUseTodo {
    setTodo: (value: string) => void;
    setTodoList: () => void;
    removeTodo: (id: number) => void;
    setStatus: (id: number) => void;
    setDoing: (id: number) => void;
}

interface IUseLocalStorage {
    getLocalList: () => ITodo[];
    setLocalList: (todoList: ITodo[]) => void;
}
function UseTodo(): IUseTodo {

    const store: Store<any> = useStore();
    const { getLocalList, setLocalList }: IUseLocalStorage = useLocalStorage();
    const todoList: ITodo[] = getLocalList();

    watch(() => {
        return store.state.list;
    }, (todoList: ITodo[]) => {
        setLocalList(todoList);
    });
    function setTodo(value: string): void {
        const SET_TODO: string = 'SET_TODO';
        const todo: ITodo = {
            id: new Date().getTime(),
            content: value,
            status: TODO_STATUS.WILLDO
        }

        store.dispatch(SET_TODO, todo);
        // setLocalList(store.state.list);
    }

    function setTodoList() {
        const SET_TODO_LIST: string = 'SET_TODO_LIST';
        store.dispatch(SET_TODO_LIST, todoList);
        // console.log(store.state.list);
    }

    function removeTodo(id: number): void {
        const REMOVE_TODO: string = 'REMOVE_TODO';
        //    console.log('removeTodo');
        store.dispatch(REMOVE_TODO, id);
        // setLocalList(store.state.list);

    }

    function setStatus(id: number): void {
        const SET_TODO_STATUS: string = 'SET_TODO_STATUS';
        // console.log('setStatus');
        store.dispatch(SET_TODO_STATUS, id);
        // setLocalList(store.state.list);
    }

    function setDoing(id: number): void {
        const SET_DOING_STATUS: string = 'SET_TODO_DOING';
        // console.log('setDoing');
        store.dispatch(SET_DOING_STATUS, id);
        // setLocalList(store.state.list);
    }

    return {
        setTodo,
        setTodoList,
        removeTodo,
        setStatus,
        setDoing
    }
}


function useLocalStorage(): IUseLocalStorage {
    function getLocalList(): ITodo[] {
        return JSON.parse(localStorage.getItem('todoList') || '[]');
    }

    function setLocalList(todoList: ITodo[]): void {
        localStorage.setItem('todoList', JSON.stringify(todoList));
    }

    return {
        getLocalList,
        setLocalList
    }
}

export {
    UseTodo,
    useLocalStorage
}
